<template>
    <div class="app-container">
      <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="机称构名" prop="deptName">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入机构名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        
      </el-form>
   -->
      <el-row :gutter="10" class="right_box">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd">新增机构</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleImport">导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
           >导出</el-button>
           <!--  @click="handleExport" -->
        </el-col>
        <el-col :span="1.5">
          <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
           <span> <el-button type="primary" plain size="mini"
           >更多操作</el-button></span>
            <el-dropdown-menu slot="dropdown">
            <router-link to="/user/profile">
                <el-dropdown-item @click.native="">
                     <span>合并</span>
                </el-dropdown-item>
            </router-link>
            <el-dropdown-item divided @click.native="">
                <span>停用</span>
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="">
                <span>删除</span>
            </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
          >展开/折叠</el-button>
        </el-col> -->
      </el-row>
  
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="orgtList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'dson', hasChildren: 'hasChildren'}"
      >
      <!--  @selection-change="handleSelectionChange"
        @select-all="handleSelectAll"
        @select="handleRowSelect" -->
        <!-- <el-table-column type="selection"width="55"></el-table-column> -->
        <el-table-column prop="institutionName" label="机构名称" min-width="260px" align="left" show-overflow-tooltip fixed="left" >
          <template slot-scope="scope">
              <el-checkbox v-model="scope.row"
                          @change="handleCheckedOne(scope.row)"/><span style="margin-left:10px">{{ scope.row.institutionName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="institutionNumber" label="机构编号" width="160"></el-table-column>
        <el-table-column prop="administrationRank" label="行政级别" width="160"></el-table-column>
        <el-table-column prop="classification" label="机构等级" width="160"></el-table-column>
        <el-table-column prop="xzPeople" label="行政负责人" width="160"></el-table-column>
        <el-table-column prop="dwPeople" label="党务负责人" width="160"></el-table-column>
        <el-table-column prop="phone" label="行政负责人电话号码" width="160"></el-table-column>
        <el-table-column prop="dwphone" label="党务负责人电话号码" width="160"></el-table-column>
        <el-table-column prop="pinstitutionPlace" label="办公地址" width="160"></el-table-column>
        <el-table-column prop="finalizationNumber" label="定编总人数" width="160"></el-table-column>
        <el-table-column prop="maxNumber" label="在岗人数" width="160"></el-table-column>
        <el-table-column prop="settingNumber" label="在编人数" width="160"></el-table-column>
        <el-table-column prop="stateValue" label="状态" width="160">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.stateValue === '正常' ? 'primary' : 'danger'"
              disable-transitions>{{scope.row.stateValue}}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table> 
  
      <!-- 添加或修改组织对话框 -->
     <el-dialog :title="title" :visible.sync="open" width="65%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="机构名称" prop="institutionName">
                <el-input v-model="form.institutionName" placeholder="请输入机构名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构编码" prop="institutionNumber">
                <el-input v-model="form.institutionNumber" placeholder="请输入机构编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="行政级别" prop="classification">
                <el-select v-model="form.classification" placeholder="机构等级" clearable>
                  <el-option v-for="dict in etElevelDict" :key="dict.dictionaryValue" :label="dict.name"
                    :value="dict.dictionaryValue" />
                </el-select>
               
              </el-form-item>
             
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构等级" prop="administrationRank">
                <el-input v-model="form.administrationRank" placeholder="请输入" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12"> 
              <div @click="xzOpen = true" class="items">
                  <el-form-item label="行政负责人" prop="xzPeople">
                      <el-input v-model="form.xzPeople" placeholder="请选择"
                          style="width: 100%" suffix-icon="el-icon-circle-plus"/>
                  </el-form-item>
              </div>
            </el-col>
            <el-col :span="12"> 
              <div @click="dwOpen = true" class="items">
                  <el-form-item label="党务负责人" prop="dwPeople">
                      <el-input v-model="form.dwPeople" placeholder="请选择"
                          style="width: 100%" suffix-icon="el-icon-circle-plus"/>
                  </el-form-item>
              </div>
            
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="行政负责人电话" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="党务负责人电话" prop="dwPhone">
                <el-input v-model="form.dwPhone" placeholder="请输入" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="办公地址" prop="institutionPlace">
                <el-input v-model="form.institutionPlace" placeholder="请输入" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.institutionFather!== 0">
              <el-form-item label="上级组织" prop="institutionFather">
                <Treeselect v-model="form.institutionFather" :options="orgtList" :normalizer="normalizer" placeholder="选择上级组织" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="定编人数" prop="finalizationNumber">
                <el-input v-model="form.finalizationNumber" placeholder="请输入" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="在编人数" prop="settingNumber">
                <el-input v-model="form.settingNumber" placeholder="请输入" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="在岗人数" prop="maxNumber">
                <el-input v-model="form.maxNumber" placeholder="请输入" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="组织状态" prop="stateValue">
                <el-switch v-model="form.stateValue" active-value="正常" inactive-value="停用"
                    active-color="#13ce66"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="组织描述" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入"/>
              </el-form-item>
            </el-col>
           
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog> 
      <!-- 选择人员 -->
        <el-dialog title="选择行政负责人" :visible.sync="xzOpen" append-to-body>
            <employee-select :multiple="false" @confirm="handleEmpsOk" @cancel="staffOpen = false"></employee-select>
        </el-dialog>
        <el-dialog title="选择党务负责人" :visible.sync="dwOpen" append-to-body>
            <employee-select :multiple="false" @confirm="handleEmpsOk1" @cancel="staffOpen = false"></employee-select>
        </el-dialog>
         <!-- 用户导入对话框 -->
          <!--  :action="upload.url + '?updateSupport=' + uploads.updateSupport" -->
        <el-dialog :title="uploads.title" :visible.sync="uploads.open" width="400px" append-to-body>
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" class="upload-demo"
            :action="fileUploadUrl + '?updateSupport=' + uploads.updateSupport"
            :disabled="uploads.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="tep1">
              <el-row>
                <el-col :span="24">第1步</el-col>
                <el-col :span="24"><el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                  @click="importTemplate">点击下载空的<span style="color:blue">表格模板</span></el-link></el-col>
              </el-row>
            </div>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <div class="el-upload__tip" slot="tip">
                <el-checkbox v-model="uploads.updateSupport" /> 是否更新已经存在的数据
              </div>
              <span>(仅允许导入xls、xlsx格式文件。)</span>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="uploads.open = false">取 消</el-button>
          </div>
        </el-dialog>
    </div>
  </template>
  
  <script>
  import {
  listMechanism,
  delMechanism,
  addDepartment,
 } from "@/api/hr/department";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import EmployeeSelect from "@/views/components/employeeSelect";
  import { listDictByType } from '@/api/hr/dictConfig'
  import { fileUploadUrl } from '@/api/hr/upload'
  export default {
    name: "OrgMange",
    // dicts: ['sys_archive_status'],
    components: { Treeselect,EmployeeSelect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 组织树选项
        deptOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部展开
        isExpandAll: true,
        // 重新渲染表格状态
        refreshTable: true,
        // 行政级别字典
        etElevelDict:[],
        // 查询参数
        queryParams: {
            pageNum: 1,
            pageSize: 100,
            institutionFather: undefined,
        },
        // 行政负责人选中数组
        xzPeopleids: [],
        xzOpen: false,  //行政负责人弹框
        dwOpen:false,
       
         // 表格树数据
        orgtList: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          parentId: [
            { required: false, message: "", trigger: "blur" }
          ],
          institutionName: [
            { required: true, message: "机构名称不能为空", trigger: "blur" }
          ],
          classification: [
            { required: true, message: "行政级别不能为空", trigger: "blur" }
          ],
          institutionFather: [
            { required: true, message: "请选择上级机构", trigger: "blur" }
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          dwPhone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        },
       // 用户导入参数
       uploads:{
        open:false,
        title:'',
        isUploading: false,
        // 是否更新已经存在的用户数据
         updateSupport: 0,
       },
       fileUploadUrl

      };
    },
    created() {
      this.getList();
      // 获取字典
      this.getDictData();
    },
    methods: {
      getDictData(){
         //获取机构等级字典
        listDictByType(5).then(res => {
          this.etElevelDict = res.data
        })
      },
      /** 查询组织机构列表 */
      getList() {
        this.loading = true;
        listMechanism(this.queryParams).then(response => {
          this.orgtList = this.handleTree(response.data, "id");
          this.loading = false;
        });
      },
      /** 转换组织数据结构 */
      normalizer(node) {
        if (node.dson && !node.dson.length) {
          delete node.dson;
        }
        return {
          id: node.id,
          label: node.institutionName,
          children: node.dson
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          institutionName:undefined,
          institutionNumber:undefined,
          administrationRank:undefined,
          classification:undefined,
          xzPeople:undefined,
          dwPeople:undefined,
          phone:undefined,
          dwPhone:undefined,
          institutionPlace:undefined,
          institutionFather:undefined,
          finalizationNumber:undefined,
          settingNumber:undefined,
          maxNumber:undefined,
          stateValue:undefined,
          remark:undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if (row != undefined) {
          this.form.parentId = row.id;
        }
        this.open = true;
        this.title = "新增机构";
        this.getList()
       
      },
      /** 展开/折叠操作 */
      // toggleExpandAll() {
      //   this.refreshTable = false;
      //   this.isExpandAll = !this.isExpandAll;
      //   this.$nextTick(() => {
      //     this.refreshTable = true;
      //   });
      // },
      /** 修改按钮操作 */
      // handleUpdate(row) {
      //   this.reset();
      //   getDept(row.id).then(response => {
      //     this.form = response.data;
      //     this.open = true;
      //     this.title = "修改组织";
      //     listDeptExcludeChild(row.id).then(response => {
      //       this.deptOptions = this.handleTree(response.data, "id");
      //       if (this.deptOptions.length == 0) {
      //         const noResultsOptions = { id: this.form.parentId, deptName: this.form.parentName, children: [] };
      //         this.deptOptions.push(noResultsOptions);
      //       }
      //     });
      //   });
      // },
      /** 提交按钮 */
      submitForm: function() {
        console.log(this.form)
        this.$refs["form"].validate(valid => {
          if (valid) {
            addDepartment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
           
          }
        });
        this.reset()
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal.confirm('是否确认删除').then(function() {
          return delDept(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
     //行政负责人选择  
      handleEmpsOk(ids, names) {
            //选择
            console.log(ids, names)
            this.xzOpen = false;
            this.employeeId = ids.toString();
            this.form.xzPeople = names.toString();
          
        },
      // 党务
      handleEmpsOk1(ids, names) {
            //选择
            console.log(ids, names)
            this.dwOpen = false;
            this.employeeId = ids.toString();
            this.form.dwPeople = names.toString();
          
        },
      //  导入
      handleImport(){
        this.uploads.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress (event, file, fileList) {
        this.uploads.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess (response, file, fileList) {
        this.uploads.open = false;
        this.uploads.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交导入文件
      submitFileForm () {
        this.$refs.upload.submit();
      },
      /** 下载模板操作 */
      importTemplate () {
        this.download(
          "/sc/department/downExcel",
          {
            //...this.queryParams
          },
          `mechanism_${new Date().getTime()}.xls`
        );
      },
      /** 导出文件 */
      handleExport() {
        this.download(
          "/sc/department/getExcel",
          {},
          `mechanism_${new Date().getTime()}.xls`
        );
      },
    }
  };
  </script>
  <style lang="scss" scoped>
  .right_box{
    float: right;
    margin-bottom: 20px;
  }
  ::v-deep .upload-demo{
    width: 360px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    .el-upload-dragger{
      border:0 !important;
    }
    .el-upload__tip{
      margin: 0 0 20px 0!important;
      text-align: center;
    }
  }
 </style>
  